import $store from '@/vuex'
import $http from '@/http'
import {mapkey} from '@s/webConfig.js'

// 定义地图
let map = null;
let project = "dejingtaxi";
let geolocation = new qq.maps.Geolocation(mapkey,project);

/*初始化地图
--------------------------------------------------------------------------------------*/
const initMap = (mapContainerId) => {

  let myLatlng = new qq.maps.LatLng(39.916527, 116.397128);

  let myOptions = {
    zoom:2,
    zoomControl:false,
    mapTypeControl:false,
    draggable:true,
    scrollwheel:true,
    // panControl:true,
    disableDoubleClickZoom:true,
    center:myLatlng,
    mapTypeId:qq.maps.MapTypeId.ROADMAP
  }

  map = new qq.maps.Map(document.getElementById(mapContainerId), myOptions);
  // this.mapClick()
  // this.mapDrag()
}

/*定位 
----------------------------------------------------------------------------------------*/
//定位失败后的回调函数
const showErr = ()=>{console.log('定位失败！')}
// 初始化定位
const myPos = ()=>{
    let opt = {timeout:8000}
    return new Promise((resolve,reject)=>{
        geolocation.getLocation((position)=>{
            if(position  && position.module == 'geolocation'){
                //修改地图的中心点
                resolve({
                    lat:position.lat,
                    lng:position.lng,
                    province:position.province,
                    city:position.city,
                    addr:position.addr,
                    name:position.name?position.name:position.addr
                })
                map.panTo(new qq.maps.LatLng(position.lat,position.lng))
                map.zoomTo(15)

            }else{
                reject('定位失败！')
            }
        },showErr,opt)

    })
}

//监听位置信息的改变
const watchMyPos = () =>{
    return new Promise((resolve,reject)=>{
        geolocation.watchPosition((position)=>{
            if(position  && position.module == 'geolocation'){
                //修改地图的中心点
                resolve({
                    lat:position.lat,
                    lng:position.lng,
                    province:position.province,
                    city:position.city,
                    addr:position.addr,
                    name:position.name?position.name:position.addr
                })
                map.panTo(new qq.maps.LatLng(position.lat,position.lng))
                map.zoomTo(15)
                // this.addMarker(position.lat,position.lng)
                // this.addCircleShadow(position.lat,position.lng)

            }else{
                reject('定位失败！')
            }
        })
     })
}

//清除监听
const clearrWatch =()=>{
    geolocation.clearWatch();
}

/*设置marker
-------------------------------------------------------------------------------------- */
const addMarker = ({
    lat,lng,icon,
    iconSize=null,scaleSize=[48,48],
    anchor=[24,48],
    animation =qq.maps.MarkerAnimation.DOWN
})=>{
    return new Promise((resolve,reject)=>{
            let marker = new qq.maps.Marker({
                position: new qq.maps.LatLng(lat,lng),
                draggable: false, //默认是false,设置为true可以拖拽
                autoRotation:true,
                animation: animation,
                map: map   //setMap(null) 可以清楚地图上的标注
            });

            let size =iconSize? new qq.maps.Size(...iconSize):null;
            let _anchor = new qq.maps.Point(...anchor);
            let origin = new qq.maps.Point(0, 0);
            let _scaleSize = new qq.maps.Size(...scaleSize);

            let markerIcon = new qq.maps.MarkerImage(
                    icon,
                    size, 
                    origin,
                    _anchor,
                    _scaleSize
                );
            marker.setIcon(markerIcon);
            resolve(marker)
    })
}

//移动marker
const moveMarker = ({marker,latLng,speed})=>{

        if(Object.prototype.toString.call(latLng)=="[object Array]"){
            let path = []; //path为路径坐标串
            for(let i=0;i< latLng.length;i++){
                path.push(new qq.maps.LatLng(latLng[i].lat,latLng[i].lng))
            }
            marker.moveAlong(path,speed)  //路径移动  
        }else if(Object.prototype.toString.call(latLng)=="[object Object]"){
            let _latLng = new qq.maps.LatLng(latLng.lat,latLng.lng)
            marker.moveTo(_latLng,speed)  //直线运动
        }
}

//添加圆形阴影
const addCircleShadow = (lat,lng)=>{
        let cirle = new qq.maps.Circle({
                center: new qq.maps.LatLng(lat,lng),
                radius: 500, //是圆形的半径，单位是“米“
                strokeColor:'', //指定圆形边线的颜色
                strokeWeight:1, //指定圆形边线的宽度
                // fillColor :'#0096fa', //指定圆形内部的填充颜色
                map: map
        });
        return cirle
    }


//轨迹

const addTrack = (latLngArr,strokeColor='#0096fa')=>{
    let _path=[];
    //扩展边界范围
    let latlngBounds = new qq.maps.LatLngBounds();
    for(let i=0;i<latLngArr.length;i=i+2){
        let _LatLng = new qq.maps.LatLng(latLngArr[i],latLngArr[i+1]);
        _path.push(_LatLng)
        //扩展边界范围，用来包含搜索到的Poi点
        latlngBounds.extend(_LatLng);
    }
    let polyline = new qq.maps.Polyline({
        path: _path,
        strokeColor,
        strokeWeight: 5,
        editable:false,
        map: map
    });

    //调整地图视野
    map.fitBounds(latlngBounds);
    return polyline;
}

/*event
-------------------------------------------------------------------------------------- */
// 点击地图，返回经纬度
const mapClick = ()=>{
    return new Promise((resolve,reject)=>{
        qq.maps.event.addListener(map,'click',(event)=>{
            map.panTo(new qq.maps.LatLng(event.latLng.lat,event.latLng.lng))
            resolve(event.latLng)
        })
    })
}

//拖拽地图
const mapDrag = (marker,el,callback)=>{
        qq.maps.event.addListener(map,'dragstart',()=>{
            marker.setMap(null);
            el.style.display = 'block';
        })
        qq.maps.event.addListener(map,'dragend',()=>{
            el.style.display = 'none';
            marker.setPosition(map.center)
            marker.setMap(map);
            addrResolver({lat:map.center.lat,lng:map.center.lng}).then((data)=>{
                callback(data)
            })
    })
    
}


//回到我的位置
const gotoPos = (lat,lng,marker)=>{
   let myLatlng = new qq.maps.LatLng(lat,lng);
    marker.setMap(null);
   map.panTo(myLatlng)
   marker.setPosition(myLatlng)
   marker.setMap(map);

}

/*检索服务 SearchService
-------------------------------------------------------------------------------------- */
//初始化搜索服务
let searchService = new qq.maps.SearchService({
    autoExtend:true,
    //检索成功的回调函数
    // complete: function(results) {

    //     //设置回调函数参数
    //     let pois = results.detail.pois;

    //     // 边界范围
    //     let latlngBounds = new qq.maps.LatLngBounds();

    //     for (let i = 0, l = pois.length; i < l; i++) {
    //         let poi = pois[i];
    //         //扩展边界范围，用来包含搜索到的Poi点
    //         latlngBounds.extend(poi.latLng);
    //     }

    //     console.log(results)

    //     //调整地图视野
    //     map.fitBounds(latlngBounds);
    // },
    error:()=>{console.log('搜索出错了！')}

});


// 搜索服务
const addressSearch = ({
    region = "中山",
    pageIndex = 1,
    pageCapacity = 50,
    searchType = 'keyword',
    keyword='楼,大厦,街道',
    circle,  //{lat:'',lng:'',radius:500}
    rect,  //[lat,lng,lat,lng]
    callback
})=>{
    //根据输入的城市设置搜索范围
    searchService.setLocation(region);
    //设置搜索页码
    searchService.setPageIndex(pageIndex);
    //设置每页的结果数
    searchService.setPageCapacity(pageCapacity);
    //设置成功后的回调函数
    searchService.setComplete(callback);

    if(searchType == 'keyword'){

        //根据输入的关键字在搜索范围内检索
        searchService.search(keyword);
    }else if(searchType == 'circle'){

        //根据输入的关键字在圆形范围内检索
        let _latLng = new qq.maps.LatLng(circle.lat,circle.lng);
        searchService.searchNearBy(keyword, _latLng , 1000);
    }else if(searchType == 'rect'){
        let _rect = new qq.maps.LatLngBounds(new qq.maps.LatLng(rect[0],rect[1]),new qq.maps.LatLng(rect[2],rect[3]));
        searchService.searchInBounds(keyword, _rect);
    }

}

//地址解析
const addrResolver = ({lat,lng})=>{
    return new Promise((resolve,reject)=>{
       let geocoder = new qq.maps.Geocoder({
            complete:function(result){
                console.log(`addrResolver`,result)
                resolve({
                    lat:result.detail.location.lat,
                    lng:result.detail.location.lng,
                    province:result.detail.addressComponents.province,
                    city:result.detail.addressComponents.city,
                    addr:result.detail.nearPois[0].address,
                    name:result.detail.nearPois[0].name
                })
            }
        });
        let coord=new qq.maps.LatLng(lat,lng);
        geocoder.getAddress(coord);

    })
}

/*输出
-------------------------------------------------------------------------------------- */
export {
    map,
    initMap,
    myPos,
    watchMyPos,
    clearrWatch,
    addMarker,
    addCircleShadow,
    moveMarker,
    addTrack,
    mapClick,
    mapDrag,
    addressSearch,
    gotoPos,
    addrResolver
}